﻿//第五种方法  
var idTmr;
function getExplorer() {
    var explorer = window.navigator.userAgent;
    //ie  
    if (explorer.indexOf("MSIE") >= 0 || explorer.indexOf("Trident")>=0) {
        return 'ie';
    }
    //firefox  
    else if (explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }
    //Chrome  
    else if (explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }
    //Opera  
    else if (explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }
    //Safari  
    else if (explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}

function tableToExcelMethod() {
    if (getExplorer() == 'ie') {
        var oXL = new ActiveXObject("Excel.Application");
        var oWB = oXL.Workbooks.Add();

        for (var i = 0; i < arguments.length; i++) {
            if (i == 0) {
                var xlsheet = oWB.Worksheets(1);
                var sel = document.body.createTextRange();

                var curTbl = document.getElementById(arguments[i].id);
                sel.moveToElementText(curTbl);
                //sel.collapse(true); 
                //sel.select();
                sel.execCommand("Copy");
                xlsheet.Paste();
            } else {
                var item = i + 1;
                if (item > oWB.Sheets.Count) {
                    oWB.Sheets.Add();
                }
                var sheetName = "Sheet" + item;
                oXL.Worksheets(sheetName).Activate();
                var newXlsheet = oWB.Worksheets(item);
                var newSel = document.body.createTextRange();

                var newCurTbl = document.getElementById(arguments[i].id);
                newSel.moveToElementText(newCurTbl);
                //sel.collapse(true); 
                //sel.select();
                newSel.execCommand("Copy");
                newXlsheet.Paste();
            }
            
        }
        oXL.Visible = true;

        try {
            var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
        } catch (e) {
            print("Nested catch caught " + e);
        } finally {
            oWB.SaveAs(fname);
            oWB.Close(savechanges = false);
            oXL.Quit();
            oXL = null;
            idTmr = window.setInterval("Cleanup();", 1);
        }

    } else {
        if (arguments.length > 1) {
            tablesToExcel(arguments);
        } else {
            tableToExcel(arguments[0]);
        }
    }
}

function Cleanup() {
    window.clearInterval(idTmr);
    CollectGarbage();
}

var tableToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>' +
            '<x:ExcelWorksheet><x:Name>' +
            '{worksheet}' +
            '</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>' +
            '</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>' +
            '<body>' +
            '<table>{table}</table>' +
            '</body></html>',
        base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
        format = function (s, c) {
            return s.replace(/{(\w+)}/g,
                function (m, p) { return c[p]; })
        }
    return function (table, name) {
        if (!table.nodeType) table = document.getElementById(table);
        name = table.getAttribute("data-excelTitle");
        var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
        //window.location.href = uri + base64(format(template, ctx));
        var link = document.createElement("A");
        link.href = uri + base64(format(template, ctx));
        link.download = (name || 'Workbook') + '.xls';
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
})();

//var tablesToExcel1 = (function () {
//    var uri = 'data:application/vnd.ms-excel;base64,'
//        , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>'
//        , templateend = '</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>'
//        , body = '<body>'
//        , tablevar = '<table>{table'
//        , tablevarend = '}</table>'
//        , bodyend = '</body></html>'
//        , worksheet = '<x:ExcelWorksheet><x:Name>'
//        , worksheetend = '</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>'
//        , worksheetvar = '{worksheet'
//        , worksheetvarend = '}'
//        , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
//        , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
//        , wstemplate = ''
//        , tabletemplate = '';

//    return function (table, name, filename) {
//        var tables = table;

//        var ctx = {};
//        for (var i = 0; i < tables.length; i++) {
//            wstemplate += worksheet + worksheetvar + i + worksheetvarend + worksheetend;
//            tabletemplate += tablevar + i + tablevarend;

//            ctx['worksheet' + i] = 'worksheet' + i;

//            var exceltable = tables[i];

//            if (!tables[i].nodeType) exceltable = document.getElementById(tables[i]);
//            ctx['table' + i] = exceltable.innerHTML;
//        }

//        var allTemplate = template + wstemplate + templateend;
//        var allWorksheet = body + tabletemplate + bodyend;
//        var allOfIt = allTemplate + allWorksheet;

//        //document.getElementById("dlink").href = uri + base64(format(template, ctx));
//        //document.getElementById("dlink").download = filename;
//        //document.getElementById("dlink").click();

//        var a = format(allOfIt, ctx);
//        console.log(a);

//        window.location.href = uri + base64(a);

//    }
//})();


var tablesToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,'
        , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
              + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
              + '<Styles>'
              + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
              + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
              + '</Styles>'
              + '{worksheets}</Workbook>'
        , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
        , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
        , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
        , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
    return function (tables, wbname, appname) {
        var ctx = "";
        var workbookXML = "";
        var worksheetsXML = "";
        var rowsXML = "";

        for (var i = 0; i < tables.length; i++) {
            if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
            for (var j = 0; j < tables[i].rows.length; j++) {
                rowsXML += '<Row>'
                for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
                    var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
                    var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
                    var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
                    dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
                    var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
                    dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
                    ctx = {
                        attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : ''
                        , nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String'
                        , data: (dataFormula) ? '' : dataValue
                        , attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
                    };
                    rowsXML += format(tmplCellXML, ctx);
                }
                rowsXML += '</Row>'
            }
            ctx = { rows: rowsXML, nameWS: tables[i].title || 'Sheet' + i };
            worksheetsXML += format(tmplWorksheetXML, ctx);
            rowsXML = "";
        }

        ctx = { created: (new Date()).getTime(), worksheets: worksheetsXML };
        workbookXML = format(tmplWorkbookXML, ctx);
        wbname = tables[0].getAttribute("data-excelTitle");
        var link = document.createElement("A");
        link.href = uri + base64(workbookXML);
        link.download = (wbname || 'Workbook') + '.xls';
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
})();